import { defineStore } from "pinia";
import { PermissionsState } from "/@ts/types/system";
import { MenuRouter, RouteList } from "/@ts/router/routes";
import { basicRoutes } from "/@ts/router/routes/static";
import { getRouters } from "/@ts/axios/urlApi/system";
import { filterAsyncRouter } from "/@ts/plugins/file";
import router from "/@ts/router";
export const usePermissionStore = defineStore("permission", {
  state: (): PermissionsState => {
    return {
      routes: [],
      addRoutes: [],
      defaultRoutes: [],
      topbarRouters: [],
      sidebarRouters: [],
    };
  },
  getters: {
    getRoutes() {
      return this.routes;
    },
    getAddRoutes() {
      return this.addRoutes;
    },
    getDefaultRoutes() {
      return this.defaultRoutes;
    },
    getTopbarRouters() {
      return this.topbarRouters;
    },
    getSidebarRouters() {
      return this.sidebarRouters;
    },
  },
  actions: {
    SET_ROUTES(routes: any) {
      this.addRoutes = routes;
      this.routes = basicRoutes.concat(routes);
    },
    SET_DEFAULT_ROUTES(routes: any) {
      this.defaultRoutes = basicRoutes.concat(routes);
    },
    SET_TOPBAR_ROUTES(routes: any) {
      this.topbarRouters = routes;
    },
    SET_SIDEBAR_ROUTERS(routes: any) {
      this.sidebarRouters = routes;
    },
     GenerateLocalityRoutes() {
      return new Promise((resolve) => {
        let menu = [...basicRoutes, ...RouteList];
        this.SET_SIDEBAR_ROUTERS(menu);
        this.SET_DEFAULT_ROUTES(menu);
        this.SET_TOPBAR_ROUTES(menu);
        menu.forEach((route: any) => {
          if (!route.path.includes("http")) {
            router.addRoute(route);
          }
        });
        resolve(menu);
      });
    },
    GenerateRoutes() {
      return new Promise((resolve) => {
        getRouters().then((res: any) => {
          let menu = [...basicRoutes, ...RouteList];
          const sdata = JSON.parse(JSON.stringify(res.data));
          const rdata = JSON.parse(JSON.stringify(res.data));
          const sidebarRoutes = filterAsyncRouter(sdata);
          const rewriteRoutes = filterAsyncRouter(rdata, false, true);
          // rewriteRoutes.push({ path: "*", redirect: "/404", hidden: true });
          this.SET_ROUTES(rewriteRoutes);
          let menus =[]
          if (import.meta.env.VITE_SERVER == 'false') {
            menus=   menu.concat(sidebarRoutes)
          }else{
            menus=   sidebarRoutes
          }
          this.SET_SIDEBAR_ROUTERS(menus);
          this.SET_DEFAULT_ROUTES(menus);
          this.SET_TOPBAR_ROUTES(menus);
          // 根据roles权限生成可访问的路由表
          resolve(rewriteRoutes);
        });
      });
    },
  },
});

// 遍历后台传来的路由字符串，转换为组件对象
